export enum NodeType {
    WHEN = "WHEN",
    THEN = "THEN",
    SWITCH = "SWITCH",
    If = "IF",
}

export class Stack {
    private ebp: number = 0;
    private esp: number = 0;
    // TODO: 自动增长
    private data: string[] = Array(100);

    public lastData = "";


    public pop(): string {
        if (this.esp == 0) return "";
        this.esp--;
        return this.data[this.esp]
    }

    public push(item: string) {
        this.data[this.esp] = item;
        this.esp++;
    }

    public clear() {
        this.esp = 0;
        this.ebp = 0;
        this.data = Array(100);
    }

    private getParseData(type: NodeType) {
        const start = this.ebp + 2;
        const end = this.esp;

        let list: string[] = [];
        for (let i = start; i < end; i++) {
            if (!!this.data[i]) list.push(this.data[i]);
        }

        if (list.length <= 1) return list[0]

        if (type === NodeType.SWITCH) {
            const start = list.shift();
            return `SWITCH(${start}).to(${list.join(',')})`
        } else if (type === NodeType.If) {
            return `IF(${list[0]},${list[1]},${list[2]})`
        }

        return `${type}(${list.join(',')})`
    }

    //退出当前环境,将节点数据保存在lastdata中
    public quit(type: NodeType): string {
        this.lastData = this.getParseData(type);

        const endPonit = this.data[this.ebp + 1]
        this.esp = this.ebp;
        this.ebp = Number(this.data[this.ebp]);

        return endPonit;//下一个要分析的节点
    }

    //开辟新的环境,（类似新开函数栈）
    public create() {
        this.data[this.esp] = this.ebp + "";
        this.ebp = this.esp;
        this.esp += 2;
    }

    //保存退出当前环境后要分析的节点id
    public addEndPoint(id: string) {
        this.data[this.ebp + 1] = id;
    }


}